# -*- coding: utf-8 -*-
# @Project : spacle
# @File    : send_mail.py
# @Author  : ysg
# @Time    : 2021-05-06 09:55:41
# @Desc    : 根据 Err 信息发送邮件


# 新浪邮箱：smtp.sina.com
# 新浪VIP：smtp.vip.sina.com
# 搜狐邮箱：smtp.sohu.com
# 126邮箱：smtp.126.com
# 139邮箱：smtp.139.com
# 163网易邮箱：smtp.163.com
# qq 邮箱：
# 腾讯企业邮箱：smtp.exmail.qq.com
# 腾讯企业邮箱：smtp.qq.com

import os
import smtplib
import configparser
from email.mime.text import MIMEText
from email.header import Header

localpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini')

class Send_mails:
    def __init__(self):
        self.tag_err = {}
        self.ini = configparser.ConfigParser()
        with open(localpath, encoding='utf-8-sig') as file:
            self.ini.read_file(file)
        self.sender = self.ini.get('send_mails', 'sender')
        self.receivers = self.ini.get('send_mails', 'receivers').split('|')
        self.mail_host = self.ini.get('send_mails', 'mail_host')
        self.mail_user = self.ini.get('send_mails', 'mail_user')
        self.mail_pass = self.ini.get('send_mails', 'mail_pass')
        self.message_From = self.ini.get('send_mails', 'message_From')
        self.message_To = self.ini.get('send_mails', 'message_To')
        self.mail_prot = self.ini.getint('send_mails', 'mail_port')

    def mails(self, mail_info, msg):
        sender = self.sender  # 发送邮件的人
        receivers = self.receivers  # 接收邮件人

        # 第三方SMTP服务
        mail_host = self.mail_host  # 设置发送服务器
        mail_user = self.mail_user  # 登录邮箱名
        mail_pass = self.mail_pass  # 口令（授权码）

        # 三个参数：第一个是文本内容，第二个plain设置文本格式，第三个utf-8设置编码
        message = MIMEText(msg, 'plain', 'utf-8')  # 发送邮件正文
        message['From'] = Header(self.message_From, 'utf-8')  # 发送者
        message['To'] = Header(self.message_To, 'utf-8')  # 接收者

        subject = mail_info  # 发送邮件标题
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP_SSL(mail_host, self.mail_prot)  # 发送服务器的端口号
            smtpObj.login(mail_user, mail_pass)
            smtpObj.sendmail(sender, receivers, message.as_string())
            # print('邮件发送成功', mail_info, msg)
        except smtplib.SMTPException as e:
            print(e)
            print('邮件发送失败')

    # def err_format(self, tag, err=None):
    #     if tag not in self.tag_err:
    #         if not err:
    #             self.tag_err[tag] += err + '\n'
    #         else:
    #             self.tag_err[tag] = '{} 栏目发生异常，请查看 \n '.format(tag)
    #     else:
    #         if not err:
    #             self.tag_err[tag] = err + '\n'
    #         else:
    #             self.tag_err[tag] = '{} 栏目发生异常，请查看 \n'.format(tag)


s_mails = Send_mails()
# if __name__ == '__main__':
#     mail_info = '发送邮件测试'
#     s_mails = Send_mails()
#     s_mails.mails(mail_info, 'test3 邮件')
